package com.example.weight.greenSeasons.SolidLiquid;

import com.example.weight.R;
import com.example.weight.householdWaste.StoppageClearActivity;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.researchDevelopment.OutcomingScene;
import com.example.weight.householdWaste.AbnormalRubbishActivity;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class shebeiyunxing7_1jiancharen extends AppCompatActivity {

    private TitleBar titleBar;
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView worm_incoming_incomeDate;
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");//HH:mm
    private TextView jilu, shiftStatus;
    private RadioGroup yijing_group;
    private String currentShift = null;
    private String currentEquip = null;
    private String factory;
    private StringBuilder record = new StringBuilder("");
    private Handler recordHandler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == 0){
                getRecord();
            }
        }
    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shebeiyunxing7_1jiancharen);
        //页面返回按钮
        titleBar=findViewById(R.id.titleBar);
        jilu = findViewById(R.id.jilu);
        jilu.setMovementMethod(ScrollingMovementMethod.getInstance());
        yijing_group = findViewById(R.id.yijing_group);
        shiftStatus = findViewById(R.id.shiftStatus);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });

        yijing_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Intent previousIntent = getIntent();
                factory = previousIntent.getStringExtra("factory");
                RadioButton radioButton = group.findViewById(checkedId);
                currentEquip = radioButton.getText().toString();
                String[] result = new String[]{"无问题", "有问题，填写说明"};
                AlertDialog.Builder builder3 = new AlertDialog.Builder(shebeiyunxing7_1jiancharen.this);
                builder3.setTitle("确认").setSingleChoiceItems(result, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:
                                save("");
                                break;
                            case 1:
                                View view = LayoutInflater.from(shebeiyunxing7_1jiancharen.this).inflate(R.layout.layout_remarks_dialog,null);
                                EditText etUserName = view.findViewById(R.id.et_notice);
                                Button btnLogin = view.findViewById(R.id.btn_save_notice);
                                MyDialog remakrsDialog = new MyDialog(shebeiyunxing7_1jiancharen.this);
                                remakrsDialog.setTitle("请填写备注");
                                remakrsDialog.setView(view);
                                btnLogin.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        remakrsDialog.dismiss();
                                        save(etUserName.getText().toString());
                                        dialog.dismiss();
                                    }
                                });
                                remakrsDialog.show();
                                break;
                        }
                        dialog.dismiss();
                    }
                }).setCancelable(false).show();
            }
        });

        try {
            if(Utility.belongCalendar(df.parse(df.format(new Date())), df.parse("00:00"), df.parse("12:00"))){
                currentShift = "白班";
            }else if(Utility.belongCalendar(df.parse(df.format(new Date())), df.parse("12:00"), df.parse("24:00"))){
                currentShift = "晚班";
            }else {
                currentShift = "不在时间范围内";
            }
            shiftStatus.setText("班次: "+currentShift);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //日期
        worm_incoming_incomeDate = findViewById(R.id.worm_incoming_incomeDate);
        worm_incoming_incomeDate.setText(simpleDateFormat.format(incomingDate));

        this.getRecord();
    }

    //提交按钮
    public void save(String remarks) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/solidliquidProduceEquipmentRunning/addExaminationalForm";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("syjc", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String code = jsonObject.getString("code");

                            if (code.startsWith("2"))
                                Toast.makeText(shebeiyunxing7_1jiancharen.this,
                                        "保存成功", Toast.LENGTH_SHORT).show();
                            else
                                Toast.makeText(shebeiyunxing7_1jiancharen.this,
                                        "保存失败", Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(shebeiyunxing7_1jiancharen.this,
                        "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipment_name", currentEquip);
                map.put("remarks", remarks);
                map.put("examiner", getIntent().getStringExtra("name"));
                map.put("factory",factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
        recordHandler.sendEmptyMessageDelayed(0, 500);
    }

    private void getRecord(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/solidliquidProduceEquipmentRunning/getListOnTheDay" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray datas = jsonObject.getJSONArray("data");
                            if(jilu.getText() != null){
                                record.delete(0, record.length());
                            }
                            if (!jsonObject.isNull("data")) {
                                for(int i=0;i<datas.length();i++){
                                    JSONObject data = datas.getJSONObject(i);
                                    if(!data.getString("onTime1").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("onTime1")).append("开机\n");
                                    }
                                    if(!data.getString("offTime1").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("offTime1")).append("关机\n");
                                    }
                                    if(!data.getString("onTime2").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("onTime2")).append("开机\n");
                                    }
                                    if(!data.getString("offTime2").equals("null")){
                                        record.append(data.getString("equipmentName")).append("于").append(data.getString("shift")).append(": ")
                                                .append(data.getString("offTime2")).append("关机\n");
                                    }
                                    jilu.setText(record.toString());
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(shebeiyunxing7_1jiancharen.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    class MyDialog extends AlertDialog{

        public MyDialog(@NonNull Context context) {
            super(context);
        }
    }
}